package com.sea.artefactos.service;

import java.util.List;

import javax.management.RuntimeErrorException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;



import com.sea.model.Artefacto;

import com.sea.model.repository.ArtefactosRepository;
import com.sea.model.repository.IncidenciaRepository;

import com.sea.util.Utilitario;


@SuppressWarnings("unused")
public class GestionarAFService {
	
	private ArtefactosRepository artefactosRepository;
	private IncidenciaRepository incidenciaRepository;	
	private EntityManager em;
	
	
	
	public GestionarAFService() {
		em=Utilitario.getInstance().getEntityManager();

		artefactosRepository=new ArtefactosRepository(em);

		incidenciaRepository= new IncidenciaRepository(em);
	}
	

	public void registrarArtefactos(Artefacto e) throws RuntimeException{
			EntityTransaction tx=em.getTransaction();
			try {
				tx.begin();
				
				artefactosRepository.insert(e);
				
				tx.commit();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
				tx.rollback();
				throw new RuntimeException("No se pudo registrar el artefacto");
			}
			
	}
	
	
	
	public void actualizarEstado(Artefacto e) throws RuntimeException{
		EntityTransaction tx=em.getTransaction();
		try {
			tx.begin();
			Artefacto artefactoupd=artefactosRepository.findById(e.getIdart());
			artefactoupd.setEstado(e.getEstado());
			artefactosRepository.update(artefactoupd);
			tx.commit();
		} catch (Exception e2) {
			// TODO: handle exception
			e2.printStackTrace();
			tx.rollback();
			throw new RuntimeException("Error al actualizar");
		}
	}
	
	public Artefacto buscarArtefacto(Artefacto e)throws RuntimeException{
		ArtefactosRepository artRepository=new ArtefactosRepository(em);
		Artefacto artefactobd=artRepository.findById(String.valueOf(e.getIdart()));
		if (artefactobd.getIdart()!=e.getIdart()) {
			throw new RuntimeException("Artefacto no encontrado");
		}
		return artefactobd;
	}
	
	public Artefacto buscarEnco(int id){
		
		Artefacto artefactobd=artefactosRepository.findById(id);
		
		return artefactobd;
	}
	
	
	
	public List<Artefacto> listarArtefactos(){
		return artefactosRepository.listAll();
	}
	
	
	
			
	
}
